package com.owen.he.jee.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

/**
 * html2pdf
 * @author owen.he
 */
public class HtmlToPdf {
    /**
     * @param url 要下载的网址
     * @param destPath 临时存放的本地路径
     * @param procPath wkhtmltopdf 程序安装的bin路径
     * @return
     */
    public static boolean convert(String url, String destPath, String procPath){  
    	//创建 文件
        File file = new File(destPath);  
        File parent = file.getParentFile();  
        if(!parent.exists()){  
            parent.mkdirs();  
        }  
      
        //封装参数 ，包括软件路径、URL、文件地址
        StringBuilder cmd = new StringBuilder();  
        cmd.append(procPath);  
        cmd.append(" ");  
        cmd.append(url);  
        cmd.append(" ");  
        cmd.append(destPath);  
          
        boolean result = false;
        //记录程序执行返回的信息
        Map<String,Object> procErrorMsg = new HashMap<>();
        Map<String,Object> outputErrorMsg = new HashMap<>();
        try{  
        	//执行程序
            Process proc = Runtime.getRuntime().exec(cmd.toString()); 
            //使用独立的线程输出处理过程的产生的信息
            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream(), procErrorMsg, "error");  
            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream(), outputErrorMsg, "output");  
            error.start();  
            output.start();  
            proc.waitFor();  
        }catch(Exception e){  
            result = false;  
            e.printStackTrace();  
        }  
        //错误信息记录到日志中 --- 
        String errorMsg = (String) procErrorMsg.get("error");
        if(StringUtils.isNotBlank(errorMsg)) {
        	if(("Done").equals(errorMsg)) {
        		result = true;
        	}
        }
        return result;  
    }  
    
    
    public static HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }
    
    
}

class HtmlToPdfInterceptor extends Thread{
	private InputStream is; 
	private Map<String, Object> mapMsg;
	private String key;
    
	public HtmlToPdfInterceptor() {
		
	}
	
    public HtmlToPdfInterceptor(InputStream is, Map<String, Object> mapMsg, String key){  
        this.is = is;  
        this.mapMsg = mapMsg;
        this.key = key;
    }  
      
    public void run(){  
        try{  
        	/** 打印流信息 */
            InputStreamReader isr = new InputStreamReader(is, "utf-8");  
            BufferedReader br = new BufferedReader(isr);  
            String line = null;  
            while ((line = br.readLine()) != null) {  
            	System.out.println(key+"->>>"+line.toString());
            	if(line.toString().indexOf("Done")>-1) {
            		mapMsg.put(key, "Done");
            	}
            } 
        }catch (IOException e){  
            e.printStackTrace();  
        }  
    }  
}

